import os
from datetime import datetime

from airtest.core.api import keyevent, touch, auto_setup, snapshot
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.core.api import log, auto_setup


class pocoApi:
    poco = None

    def __init__(self):
        if pocoApi.poco is None:
            pocoApi.poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
        # 项目目录
        base_path = os.path.split(os.path.dirname(__file__))[0]
        auto_setup(__file__, logdir=f"{base_path}/log")  # 设置日志目录

    def poco_click(self, sel=None, **kwargs):
        try:
            if 'text' in kwargs:
                element = self.poco(text=kwargs['text'])
                element.click()
                element_text = element.get_text()  # 获取元素的文本内容
                print(f"成功点击元素：{kwargs['text']}")
                log(f"成功点击元素：{kwargs['text']}, 元素文本：{element_text}")
                return element_text  # 返回文本内容
            else:
                element = self.poco(sel)
                element.click()
                element_text = element.get_text()  # 获取元素的文本内容
                print(f"成功点击元素：{sel}")
                log(f"成功点击元素：{sel}, 元素文本：{element_text}")
                return element_text  # 返回文本内容
        except Exception as e:
            print(f"点击元素失败：{sel if 'text' not in kwargs else kwargs['text']}, 错误信息：{e}")
            log(f"点击元素失败：{sel if 'text' not in kwargs else kwargs['text']}, 错误信息：{e}")

    def poco_text(self, sel, text):
        try:
            self.poco(sel).set_text(text)
            print(f"成功输入文本：{text}")
            log(f"输入文本成功：{text}")
        except Exception as e:
            print(f"输入文本失败：{text}, 错误信息：{e}")
            log(f"输入文本失败：{text}, 错误信息：{e}")

    def poco_wait(self, sel, timeout=10):
        try:
            self.poco(sel).wait_for_appearance(timeout=timeout)
            print(f"元素{sel}出现")
            log(f"元素{sel}出现")
        except Exception as e:
            print(f"元素{sel}未出现")
            log(f"元素{sel}未出现")

    def poco_home(self):
        keyevent("HOME")
        log("HOME")

    def poco_back(self):
        keyevent("BACK")
        log("BACK")

    def poco_swipe(self, start, end, duration=0.5):
        try:
            self.poco.swipe(start, end, duration=duration)
            print(f"成功滑动")
            log(f"成功滑动")
        except Exception as e:
            print(f"滑动失败，错误信息：{e}")
            log(f"滑动失败，错误信息：{e}")

    def poco_touch(self, x, y):
        try:
            touch((x, y))  # 使用 Airtest 的 touch 方法
            print(f"成功点击坐标：{x},{y}")
            log(f"成功点击坐标：{x},{y}")
        except Exception as e:
            print(f"点击坐标失败：{x},{y}, 错误信息：{e}")
            log(f"点击坐标失败：{x},{y}, 错误信息：{e}")

    def poco_skip_ad(self):
        try:
            if self.poco("android.widget.FrameLayout").child("android.view.View").child("android.view.View").child(
                    "android.widget.ImageView").wait(timeout=5).exists():
                self.poco("android.widget.FrameLayout").child("android.view.View").child("android.view.View").child(
                    "android.widget.ImageView").click()
            else:
                print("无广告")
                log("无广告")
        except Exception as e:
            print("跳过广告失败，错误信息：", e)
            log("跳过广告失败，错误信息：", e)

    def poco_snapshot(self):
        snapshot("test_snapshot.png", msg="这是一张测试截图")


if __name__ == '__main__':
    p = pocoApi()
    p.poco_snapshot()
